﻿using System;
using System.IO;

namespace WikiDoc.Reader
{
    /// <summary>
    /// 根据设定去掉读取的每一行的前若干字符。
    /// </summary>
    /// <remarks>
    /// 本读取器只有在一行一行进行读取时才有效。Peek 、Read 方法读取都相当于直接从原读取器中读取。
    /// </remarks>
    public class TrimReader : TextReaderPipe
    {

        /// <summary>
        /// Initializes a new instance of the TrimReader class.
        /// </summary>
        /// <param name="baseStream">The base stream.</param>
        /// <param name="trimCount">The trim count.</param>
        public TrimReader(TextReader baseStream, int trimCount)
            : base(baseStream)
        {
            if (trimCount < -1)
            {
                throw new ArgumentOutOfRangeException("trimCount","trimCount must be -1 or greater than 0" );
            }

            _TrimCount = trimCount;
        }


        private int _TrimCount;
        /// <summary>
        /// Gets the trim count.
        /// </summary>
        /// <value>The trim count.</value>
        public int TrimCount
        {
            get
            {
                return _TrimCount;
            }
            set
            {
                if (value < -1)
                {
                    throw new ArgumentOutOfRangeException("value", "trimCount must be -1 or greater than 0");
                }

                _TrimCount = value;
            }
        }

        /// <summary>
        /// 从当前流中读取一行字符并将数据作为字符串返回。
        /// </summary>
        /// <returns>输入流的下一行，或者如果已读取了所有字符，则为 null。</returns>
        /// <exception cref="T:System.IO.IOException">发生 I/O 错误。 </exception>
        /// <exception cref="T:System.OutOfMemoryException">内存不足，无法为返回的字符串分配缓冲区。 </exception>
        /// <exception cref="T:System.ObjectDisposedException"><see cref="T:System.IO.TextReader"></see> 是关闭的。 </exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">下一行中的字符数大于 <see cref="F:System.Int32.MaxValue"></see></exception>
        public override string ReadLine()
        {
            string line = BaseReader.ReadLine();

            if (line == null) return null;

            if (_TrimCount == -1)
            {
                _TrimCount = line.Length - line.TrimStart().Length;
            }

            if (_TrimCount > 0)
            {
                if (_TrimCount < line.Length)
                    line = line.Substring(_TrimCount);
                else
                    line = string.Empty;
            }

            return line;
        }

    }
}